package com.cicadasmall.config.webmvc;

import com.cicadasmall.common.constant.Constant;
import com.cicadasmall.common.utils.EvnUtils;
import com.cicadasmall.security.support.CurrentUserHandlerMethodArgumentResolver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.*;

import java.util.List;

/**
 * WebMvcConfig
 *
 * @author Jin
 */
@Slf4j
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private static final String STATIC_FOLDER = "static";

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (EvnUtils.isJarActive(WebMvcConfig.class)) {
            String staticPath = EvnUtils.checkAndCreateResourceDir(STATIC_FOLDER);
            log.info("========[ JAR方式运行设置资源路径至 - {} ]========", staticPath);
            registry.addResourceHandler("/static/**").addResourceLocations("file:" + staticPath + "/");

        } else {
            registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        }
        registry.addResourceHandler("/api/swagger/**").addResourceLocations("classpath:/META-INF/resources/");
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new CurrentUserHandlerMethodArgumentResolver());
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*")
                .allowCredentials(false)
                .maxAge(Constant.CORS_MAX_AGE)
                .allowedHeaders("*");
    }
}
